package com.tool.app.utils;

//import com.aspose.words.Document;
//import com.aspose.words.License;
//import com.aspose.words.SaveFormat;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Word 转 Pdf 工具类
 *
 * @author admin
 */
public class WordToPdfUtil {
	private static boolean license = false;

	public static void main(String[] args) throws FileNotFoundException {
		String basePath = ResourceUtils.getURL("classpath:").getPath() + "static/";
		doc2pdf("E:\\aab.doc", basePath + "ab.pdf");
	}

	static {
		try {
			// license.xml放在src/main/resources文件夹下
			InputStream is = WordToPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
//			License aposeLic = new License();
//			aposeLic.setLicense(is);
//			license = true;
		} catch (Exception e) {
			license = false;
			System.out.println("License验证失败...");
			e.printStackTrace();
		}
	}

	/**
	 * doc转pdf
	 *
	 * @param wordPath
	 * @param pdfPath
	 */
	public static void doc2pdf(String wordPath, String pdfPath) {
		// 验证License 若不验证则转化出的pdf文档会有水印产生
		if (!license) {
			System.out.println("License验证不通过...");
			return;
		}

		try {
			long old = System.currentTimeMillis();
			//新建一个pdf文档
			File file = new File(pdfPath);
			FileOutputStream os = new FileOutputStream(file);
			//Address是将要被转化的word文档
//			Document doc = new Document(wordPath);
//			//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
//			doc.save(os, SaveFormat.PDF);
			long now = System.currentTimeMillis();
			os.close();
			//转化用时
			System.out.println("Word 转 Pdf 共耗时：" + ((now - old) / 1000.0) + "秒");
		} catch (Exception e) {
			System.out.println("Word 转 Pdf 失败...");
			e.printStackTrace();
		}
	}

	/**
	 * 合并pdf
	 * @param pdfPathList
	 * @param fileName
	 * @return
	 */
	public String MulFileToOne(List<String> pdfPathList, String fileName) {
		String pdfSuffix = ".pdf";
		String resultPpdfPath = fileName + pdfSuffix;//pdf文件路径
		List<File> files = new ArrayList<>();
		try {
			PDFMergerUtility mergePdf = new PDFMergerUtility();
			for (String s : pdfPathList) {
				File f = new File(s);
				if (f.exists() && f.isFile()) {
					files.add(f);
					//循环添加要合并的pdf
					mergePdf.addSource(f);
				}
			}
			// 设置合并生成pdf文件名称
			mergePdf.setDestinationFileName(resultPpdfPath);
			// 合并pdf
			mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
		} catch (IOException e) {
			// logger.error("合并PDF失败",e);
			throw new RuntimeException(e);
		}finally {
			for (File file : files) {
				file.delete();
			}
		}
		return resultPpdfPath;
	}
}